package main

import (
	"fmt"
	"os"
	"io"
	"bufio"
	"strings"
)

type CifsShareInfo struct {
	Name string
	InfoMap map[string]string
}

var shareList []CifsShareInfo

func main() {
	fmt.Println(uuid)
	loadCifsConfigFile()
	saveCifsConfigFile()
	return
}

func loadCifsConfigFile() {
	var shareIndex int
	//只读方式打开
	fileRead, err := os.OpenFile("./smb.conf", os.O_RDONLY, 0440)
	if err != nil {
		fmt.Println("fail to open the file", err)
	}
	fmt.Println("success to open the file")
	defer fileRead.Close()
	reader := bufio.NewReader(fileRead)

	shareIndex = -1
	for {
		// 行数据
		line, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		}
		// 去除行首行尾的无效字符串 
		content := strings.Trim(line, "\n\t \r")
		// 忽略空行及注释行
		if len(content) == 0 || content[0] == '#' || content[0] == ';' {
			continue
		}
		// new share
		if content[0] == '[' {
			shareIndex++
			shareList = append(shareList, CifsShareInfo{})
			shareList[shareIndex].InfoMap = make(map[string]string)
			shareList[shareIndex].Name = strings.Trim(content, "[]")
			//fmt.Println("----", shareIndex, shareList[shareIndex].Name)
		} else {
			paramter := strings.Split(content, "=")
			key := strings.TrimSpace(paramter[0])
			value := strings.TrimSpace(paramter[1])
			//fmt.Println("----", "key=", key, "value=", value)
			shareList[shareIndex].InfoMap[key] = value 
		}
		//fmt.Println(">>>", content)
	}

	for _, share := range shareList {
		fmt.Println("===Name:", share.Name)
		for k,v := range share.InfoMap {
			fmt.Printf("%v=%v\n",k,v)
		}
	}

	return 
}

func saveCifsConfigFile() error {
	fileWrite, err := os.OpenFile("./bk_smb.conf", os.O_WRONLY | os.O_CREATE, 0660)
	if err != nil {
		fmt.Println("fail to open the file", err)
	}

	fmt.Println("success to open the file to write")
	defer fileWrite.Close()
	writer := bufio.NewWriter(fileWrite)

	for _, share := range shareList {
		name := "[" + share.Name + "]" + "\n"
		if _, err = writer.WriteString(name); err != nil {
			return err
		}

		for k,v := range share.InfoMap {
			parameter :="\t" + k + " = " + v + "\n"
			if _, err = writer.WriteString(parameter); err != nil {
				return err
			}
		}
	}

	if err = writer.Flush(); err != nil {
		return err
	}

	return nil
}
